//
//  TransferOutController.m
//  SafPay
//
//  Created by 贺庆博 on 2018/6/19.
//  Copyright © 2018年 ebo. All rights reserved.
//

#import "TransferOutController.h"
#import "TransferOutTopView.h"
#import "TransferOutCenterView.h"
#import "TransferOutBottomView.h"
#import "NewTransferOutViewModel.h"
#import "TDTitleBtn.h"
#import "AddressModel.h"
#import "CoinModel.h"
#import "CoinDetailModel.h"
#import "TransferOutModel.h"
#import "ChoseCoinController.h"
#import "WalletDetailsController.h"
#import "VerPwdController.h"
//#import "AddViewController.h"
//#import "AddressListViewController.h"
//#import "TransferOutCell.h"
//#import "TransferOutMoenyCell.h"
//#import "TransferOutAddressCell.h"
#import "WJTools.h"
//#import "MyInfoTools.h"
//#import "MeumView.h"
#import "WCQRCodeScanningVC.h"
@interface TransferOutController ()<UITableViewDataSource,UITableViewDelegate>
{
    
    
}
@property (nonatomic,strong) UIButton *turnOutBtn;

@property (nonatomic, assign) BOOL isBlock;
@property (nonatomic,strong) UITableView *backTableView;
@property (nonatomic,strong) TransferOutTopView *topView;
@property (nonatomic,strong) TransferOutCenterView *centerView;
@property (nonatomic,strong) TransferOutBottomView *bottomView;
@property (nonatomic,strong) NewTransferOutViewModel *viewModel;
@property (nonatomic, weak) TDTitleBtn *rightbtn;
//@property (nonatomic,strong) TransferOutModel *model;
@property (strong,nonatomic) NSMutableArray *blockArray;
@property (nonatomic , strong)dispatch_source_t timer;
@property (nonatomic, strong) NSMutableArray *coins;
@property (nonatomic, strong) CoinModel *selectModel;
@property (strong,nonatomic) NSMutableArray *dataArray;
@property (nonatomic,strong) TransferOutInfoModel *myModel;


@end

@implementation TransferOutController
#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.myModel.type = self.type;
    self.myModel.money = self.money;
    [self initUI];
    [self initData];
    self.backTableView.scrollEnabled = NO;
    [self startTimer];
   
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.timer) {
        dispatch_cancel(self.timer);
        
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.timer) {
        [self startTimer];
        
    }
    
}
- (void)loadData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.type forKey:@"coinname"];
    [dic setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
    [dic setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
    [dic setValue:self.wid forKey:@"wid"];
    [[TRRequest request] Post:kSetURL(kCoinDetails) parameters:dic success:^(TRRequest *request, NSDictionary *responseDict) {
        
        if ([[responseDict valueForKey:@"error"] integerValue] == 0) {
            NSDictionary *dict = [responseDict valueForKey:@"data"];
            self.myModel.num = [dict valueForKey:@"coin_num"];
            [self.topView setModel:self.myModel];
            
        }
//        else
//        {
//            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
//        }
    } failure:^(TRRequest *request, NSError *error) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initData
{
    [self.centerView setModel:self.myModel];
    [self.topView setModel:self.myModel];
    [self.bottomView setModel:self.myModel];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.type forKey:@"coinname"];
    [dic setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
    [dic setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
    [[TRRequest request] Post:kSetURL(kOutInfo) parameters:dic success:^(TRRequest *request, NSDictionary *responseDict) {
        if ([[responseDict valueForKey:@"error"] integerValue] == 0) {
//            [self.myModel setValuesForKeysWithDictionary:[responseDict valueForKey:@"data"]];
            [self.myModel yy_modelSetWithDictionary:[responseDict valueForKey:@"data"]];
            self.myModel.num=self.money;
            [self.centerView setModel:self.myModel];
            [self.topView setModel:self.myModel];
            [self.bottomView setModel:self.myModel];
        }else
        {
            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
        }
    } failure:^(TRRequest *request, NSError *error) {
        
        [MBProgressHUD showErrorWithText:@"网络请求失败！"];
    }];
}

#pragma mark - Network
//- (void)load:(NSString *)walletid{
//    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//
//    [dic setValue:walletid forKey:@"type"];
//    [WJHttpTools postRequestWithPara:dic path:kSetURL(kCoinDetails) success:^(id responseObject) {
//        if (![[responseObject valueForKey:@"error"] intValue]) {
//            NSDictionary *dic = [responseObject valueForKey:@"data"];
//            CoinDetailModel *model = [[CoinDetailModel alloc]init];
//            //[model yy_modelSetWithDictionary:dic];
//            [model setValuesForKeysWithDictionary:dic];
//            self.model.model = model;
//            self.model.model.num = [NSString stringWithFormat:@"%@",model.num];
//            [self.topView setModel:self.model.model];
//            [self.centerView setModel:self.model];
//            [self.bottomView setModel:self.model];
//            [self.rightbtn setTitle:model.type  forState:UIControlStateNormal];
//
//        }
//    } failure:^(id error) {
//
//    }];
//}
////黑名单
//- (void)blackListwithId:(NSString *)addressId {
//    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    [dic setValue:addressId forKey:@"id"];
//    [WJHttpTools postRequestWithPara:dic path:kSetURL(kBlackTransferAddresses) success:^(id responseObject) {
//
//        if (![[responseObject valueForKey:@"error"] intValue]) {
//            NSArray *data = [responseObject valueForKey:@"data"];
//            [self.blockArray removeAllObjects        ];
//            [self.blockArray addObjectsFromArray:data];
//            [MyInfoTools saveBlackList:data];
//        }
//    } failure:^(id error) {
//
//    }];
//
//
//}
//- (void)loadData:(void(^)(NSMutableArray *items))success{
//    [WJHttpTools postRequestWithPara:nil path:kSetURL(kCoinList) success:^(id responseObject) {
//        if (![[responseObject valueForKey:@"error"] intValue]) {
//            NSArray *data = [responseObject valueForKey:@"data"];
//            NSMutableArray *items = [NSMutableArray array];
//            for (NSDictionary *dic in data) {
//                CoinModel *model = [CoinModel new];
//                [model yy_modelSetWithDictionary:dic];
//
//                [self.coins addObject:model];
//            }
//
//            self.coins=[self orderListArr:self.coins];
//
//            for (CoinModel *model in self.coins){
//                [items addObject:model.coin];
//            }
//
//            if (success) {
//                success(items);
//            }
//        }
//    } failure:^(id error) {
//
//    }];
//}
#pragma mark - Lazy
- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)coins{
    if (!_coins) {
        _coins = [NSMutableArray array];
    }
    return _coins;
}
//- (TransferOutModel *)model{
//    if (!_model) {
//        _model = [[TransferOutModel alloc]init];
//    }
//    return _model;
//}
-(NewTransferOutViewModel *)viewModel{
    
    if(!_viewModel){
        
        _viewModel=[NewTransferOutViewModel new];
    }
    return _viewModel;
}
-(UITableView *)backTableView{
    
    if(!_backTableView){
        _backTableView=[[UITableView alloc]init];
        [_backTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_backTableView setDelegate:self];
        [_backTableView setDataSource:self];
        [_backTableView setBackgroundColor:rgb(255, 255, 255)];
    }
    return _backTableView;
}
-(TransferOutTopView *)topView{
    
    if(!_topView){
        
        _topView=[[TransferOutTopView alloc]init];
        
    }
    return _topView;
}
-(TransferOutCenterView *)centerView{
    
    if(!_centerView){
        
        __weak TransferOutController * weakSelf=(TransferOutController *)self;
        
        _centerView=[[TransferOutCenterView alloc]init];
        _centerView.getAmountBlock = ^(NSString *str) {
            weakSelf.myModel.amount = str.length?str:@"0";

            [weakSelf.centerView setModel:weakSelf.myModel];
        };
        _centerView.addressChangeBlock = ^(NSString *str) {
            if(weakSelf.myModel.addressModel==nil){
                
                weakSelf.myModel.addressModel=[[AddressModel alloc]init];
            }
            weakSelf.myModel.addressModel.address = str;
            [weakSelf.centerView setModel:weakSelf.myModel];
        };
        _centerView.addAddressBlock = ^{
            
            WCQRCodeScanningVC *vc = [[WCQRCodeScanningVC alloc]init];
            
            vc.QRblock = ^(NSString *str) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                BOOL isBlock = NO;
//                for (NSString *address in [MyInfoTools getBlackList]) {
//                    if ([str isEqualToString:address]) {
//                        isBlock = YES;
//                    }
//                }
                weakSelf.isBlock = isBlock;
                //                weakSelf.model.address = str;
                //                [self.tableView reloadData];
                if(weakSelf.myModel.addressModel==nil){
                    
                    weakSelf.myModel.addressModel=[[AddressModel alloc]init];
                }
                [weakSelf.myModel.addressModel setAddress:str];
                [AddressModel saveAddressModel:weakSelf.myModel.addressModel];
                BOOL block = NO;
                for (NSString *address in weakSelf.blockArray) {
                    if ([str isEqualToString:address]) {
                        block = YES;
                    }
                }
                weakSelf.isBlock =isBlock;
                [weakSelf.centerView setModel:weakSelf.myModel];
            };
            
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
    }
    return _centerView;
}
-(TransferOutBottomView *)bottomView{
    
    kWeakSelf(weakSelf);
    if(!_bottomView){
        
        _bottomView=[[TransferOutBottomView alloc]init];
        _bottomView.btnBlock = ^{
            
            [weakSelf btnAction];
        };
        
    }
    return _bottomView;
}
- (NSMutableArray *)blockArray{
    if (!_blockArray) {
        _blockArray = [NSMutableArray array];
    }
    return _blockArray;
}
#pragma mark - Privacy
//定时器轮询
- (void)startTimer
{
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建一个定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)([GTimeLength floatValue] * NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIApplicationState state = [UIApplication sharedApplication].applicationState;
            if (state == UIApplicationStateActive){
                [self loadData];
            };
        });
    });
    //启动定时器
    dispatch_resume(self.timer);
}
-(void)initUI{
    
    self.title=@"转出";
    self.myModel.num=@"";
    self.myModel.zc_min=@"";
    self.myModel.zc_min_fee=@"";
    [self.view addSubview:self.backTableView];
    [self createRightBtn];
    [self.backTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(20, 26, 65,26));
    }];
    [self.view addSubview:self.turnOutBtn];
    [self.turnOutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
}
-(void)createRightBtn{
    
    TDTitleBtn * rightbtn = [[TDTitleBtn alloc]initWithFrame:CGRectMake(kScreenWidth - 80 - 15, kNavHeight - 35, 80, 23)];
    rightbtn.layer.cornerRadius = 11;
    rightbtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    rightbtn.titleLabel.textAlignment = 1;
    rightbtn.titleLabel.font = kFONT(12);
    [rightbtn setTitle:self.type?:@"--" forState:UIControlStateNormal];
    [rightbtn setImage:kImageName(@"arrow_down") forState:UIControlStateNormal];
    [rightbtn setImage:kImageName(@"arrow_up") forState:UIControlStateSelected];
    rightbtn.layer.borderColor = [kTradeWhiteColor CGColor];
    rightbtn.layer.borderWidth = 0.5f;
    [rightbtn addTarget:self action:@selector(rightnBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.rightbtn = rightbtn;
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:rightbtn];
    
    
}

//先冒泡后排序
- (NSMutableArray*)orderListArr:(NSMutableArray*)arr
{
    
    for (int i =0; i < arr.count; i ++) {
        for (int j = i +1; j < arr.count; j ++) {
            CoinModel   *imodel= arr[i];
            CoinModel *jmodel = arr[j];
            
            if ([imodel.cny_price doubleValue]<[jmodel.cny_price doubleValue]) {
                
                [arr exchangeObjectAtIndex:i withObjectAtIndex:j];
            }
        }
        
    }
    
    NSMutableArray *array = [NSMutableArray arrayWithArray:arr];
    __block CoinModel *ccnyModel;
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CoinModel *dic=(CoinModel *)obj;
        if ([dic.coin isEqualToString:@"CCNY"]) {
            ccnyModel = dic;
            [array removeObject:dic];
            [array insertObject:dic atIndex:0];
        }
        if ([dic.coin isEqualToString:@"BTCH"]) {
            if ([array containsObject:ccnyModel]) {
                [array removeObject:dic];
                [array insertObject:dic atIndex:1];
            }else
            {
                [array removeObject:dic];
                [array insertObject:dic atIndex:0];
            }
        }
    }];
    return array;
}
- (void)coinAction:(UIButton *)btn{
    NSMutableArray *items=[[NSMutableArray alloc]init];
    [self.coins enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        CoinModel *model=(CoinModel *)obj;
        [items addObject:model.coin];
    }];
    
    btn.selected = YES;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    CGRect rect=[btn convertRect: btn.bounds toView:window];
    
    
}
- (void)rightnBtnClick
{
    ChoseCoinController *vc = [ChoseCoinController new];
    
    vc.coinClickBlock = ^(CoinListModel *model) {
        self.type = model.name;
        self.myModel.type = model.name;
        [self.rightbtn setTitle:model.name forState:UIControlStateNormal];
        
        [self initData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)btnAction{
    
    self.myModel.amount=self.centerView.numTextField.text;
    if ([WJTools isBlankString:self.myModel.amount]) {
        [MBProgressHUD showSuccessWithText:@"Please fill in the transfer amount"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.myModel.addressModel.address forKey:@"address"];
    [dic setValue:self.myModel.amount forKey:@"amount"];
    [dic setValue:self.myModel.type forKey:@"name"];
    
//    [WJHttpTools postRequestWithPara:dic path:kSetURL(kTransferOut) success:^(id responseObject) {
//        if (![[responseObject valueForKey:@"error"]intValue]) {
//            NSString *status = [[responseObject valueForKey:@"data"] valueForKey:@"status"];
//            [MBProgressHUD showSuccessWithText:status];
//
//            [self.navigationController popViewControllerAnimated:YES];
//        }else{
//            [MBProgressHUD showErrorWithText:[responseObject valueForKey:@"error_msg"]];
//        }
//    } failure:^(id error) {
//
//    }];
}

#pragma mark - UITableView Delegate and Datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.row==0){
        
        return kSCALE_WIDTH(50);
        
    }else if (indexPath.row==1){
        
        return kSCALE_WIDTH(245);
    }
    else{
        return  kScreenHeight-kSCALE_WIDTH(305)-kNavHeight;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell=[[UITableViewCell alloc]init];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//    [cell setBackgroundColor:kSetColor(@"1e2235")];
    switch (indexPath.row) {
        case 0:
        {
            [cell.contentView addSubview:self.topView];
            [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.top.right.bottom.equalTo(cell.contentView);
            }];
        }
            break;
            
        case 1:
        {
            [cell.contentView addSubview:self.centerView];
            [self.centerView mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.top.right.bottom.equalTo(cell.contentView);
            }];
        }
            break;
        case 2:
        {
            [cell.contentView addSubview:self.bottomView];
            [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.bottom.equalTo(cell.contentView);
                
            }];
        }
            break;
            
        default:
            break;
    }
    return cell;
}

-(UIButton *)turnOutBtn{
    
    if(!_turnOutBtn){
        
        _turnOutBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [_turnOutBtn setBackgroundColor:rgb(33,177,227)];
        [_turnOutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_turnOutBtn setTitle:@"确认转出" forState:UIControlStateNormal];
        [_turnOutBtn.titleLabel setFont:FONT(15)];
        [_turnOutBtn addTarget:self action:@selector(turnOutBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }

    return _turnOutBtn;
}
- (void)turnOutBtnClick
{
    if(self.myModel.addressModel.address.length==0){
        
        [MBProgressHUD showErrorWithText:@"转出地址不能为空"];
        return;
    }
    if ([self.myModel.amount floatValue] > [self.myModel.money floatValue]) {
        [MBProgressHUD showErrorWithText:@"余额不足"];
        return;
    }
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if ([self.myModel.amount floatValue] < [self.myModel.zc_min floatValue]) {
        [MBProgressHUD showErrorWithText:[@"转账数量不能低于" stringByAppendingString:self.myModel.zc_min]];
        return;
    }
    if ([self.myModel.amount floatValue] > [self.myModel.zc_max floatValue]) {
        [MBProgressHUD showErrorWithText:[@"转账数量不能高于" stringByAppendingString:self.myModel.zc_max]];
        return;
    }
    VerPwdController *vc=[VerPwdController new];
    vc.myModel=self.myModel;
    [self.navigationController pushViewController:vc animated:YES];
//    [dic setValue:self.myModel.type forKey:@"coinname"];
//    [dic setValue:[AccountTools shared].currentAccount.token forKey:@"token"];
//    [dic setValue:[AccountTools shared].currentAccount.userId forKey:@"uid"];
//    [dic setValue:self.myModel.addressModel.address forKey:@"address"];
//    [dic setValue:self.myModel.amount forKey:@"amount"];
//
//    [[TRRequest request] Post:kSetURL(kTransferOut) parameters:dic success:^(TRRequest *request, NSDictionary *responseDict) {
//
//        if ([[responseDict valueForKey:@"error"] integerValue] == 0) {
//            [self.navigationController popViewControllerAnimated:YES];
//            [MBProgressHUD showSuccessWithText:@"转出成功"];
//
//        }else
//        {
//            [MBProgressHUD showErrorWithText:[responseDict valueForKey:@"error_msg"]];
//        }
//    } failure:^(TRRequest *request, NSError *error) {
//
//        [MBProgressHUD showErrorWithText:@"网络连接失败！"];
//    }];
}
- (TransferOutInfoModel *)myModel
{
    if (!_myModel) {
        _myModel = [TransferOutInfoModel new];
    }
    return _myModel;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
